package cn.jn.lhm.netty.part08.chat.handler;

import cn.jn.lhm.netty.part08.chat.message.GroupCreateRequestMessage;
import cn.jn.lhm.netty.part08.chat.message.GroupCreateResponseMessage;
import cn.jn.lhm.netty.part08.chat.session.Group;
import cn.jn.lhm.netty.part08.chat.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/11/1 - 20:18
 **/
@ChannelHandler.Sharable
@Slf4j
public class ServerCreateGroupMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        // 创建群聊
        Group group = GroupSessionFactory.getGroupSession().createGroup(groupName, msg.getMembers());
        // 说明创建成功了
        if (group == null) {
            List<Channel> channels = GroupSessionFactory.getGroupSession().getMembersChannel(groupName);
            for (Channel channel : channels) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true, "欢迎加入" + groupName));
            }
        } else {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, "群聊已存在"));
        }
    }
}
